###########################################################################
#       Copyright (C) 2008 Timothy Clemans <timothy.clemans@gmail.com>
#
#   Released under the New BSD license.
#
###########################################################################

import cell

def make_pre_mod(data, direction):
    """
    
    """
    data = make_lis_of_lists(data)
    data = make_eq_size(data)
    data = change_direction(data, direction)
    return make_cells(data)
    
def make_lis_of_lists(data):
    """
    
    """
    return map(list, data)

def change_direction(data, direction):
    """Transposes data if direction is 'col' otherwise data is returned. data is
    assumed to be a list of lists.
    
    EXAMPLES:
        >>> change_direction([(i for i in range(5))], 'col')
        [[0], [1], [2], [3], [4]]
        >>> change_direction([(i for i in range(5))], 'row')
        [[0, 1, 2, 3, 4]]
        >>> change_direction(range(5), 'col')
        Traceback (most recent call last):
        TypeError: data must be a list of lists
        >>> change_direction([(i for i in range(5))], 'left')
        Traceback (most recent call last):
        KeyError: "direction 'left' is not recognized"
    """
    try:
        if direction == 'row':
            return data
        elif direction == 'col':
            return map(list, zip(*data))
        else:
            raise KeyError, "direction '%s' is not recognized" % direction
    except TypeError:
        raise TypeError, 'data must be a list of lists'
    
def make_eq_size(data):
    """Returns a list of lists of equal length given a list of lists. 
    
    EXAMPLES:
        >>> make_eq_size([range(i) for i in range(1, 5)])
        [[0, None, None, None], [0, 1, None, None], [0, 1, 2, None], [0, 1, 2, 3]]
        >>> make_eq_size([range(i) for i in [5, 1, 3, 5]])
        [[0, 1, 2, 3, 4],
         [0, None, None, None, None],
         [0, 1, 2, None, None],
         [0, 1, 2, 3, 4]]
    """
    n_of_cols = max(map(len, data))
    return [i + [None] * (n_of_cols - len(i)) for i in data]

def make_cells(data):
    """Returns list of lists of cells.
    
    """
    return [[cell.Cell(col) for col in row] for row in data]